/*
 * @Project Name: shoplook
 * @File Name: FileUtil
 * @Package Name: com.sm.shoplook.util
 * @Date: 2018/8/13 15:57
 * @Creator: linshixing-1199
 * @line------------------------------
 * @修改人:
 * @修改时间:
 * @修改内容:
 */

package com.sm.shoplook.util;

import com.sm.shoplook.config.ProjectProperties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author chenpy
 * @desc 文件工具类
 * @date 2018/8/13 15:57
 * @see
 */
@Component
public class FileUtil {

	@Autowired
	private ProjectProperties projectProperties;
	private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

	/**
	 * 文件上传
	 * @param multipartFile
	 * @return
	 */
	public String uploadFile(MultipartFile multipartFile) {
		if (multipartFile != null && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
			try {
				String parentDirPath = projectProperties.getFileConfig().getFileRootUploadPath();
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
				String date = simpleDateFormat.format(new Date());
				File parentDir = new File(parentDirPath);
				if (!parentDir.exists()) {
					FileUtils.forceMkdir(parentDir);
				}
				String fileName = date + "_" + System.currentTimeMillis() + "_"
						+ Base64Utils.encodeToString(multipartFile.getOriginalFilename().getBytes("UTF-8"));
				String extName = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
				if (StringUtils.isEmpty(extName)) {
					extName = "png";
				}
				File file = new File(parentDirPath + "/" + fileName + "." + extName);
				LOGGER.info("上传文件file: {}", file.getAbsolutePath());
				multipartFile.transferTo(file);
				LOGGER.info("image url: {}", projectProperties.getFileConfig().getFileRootImagesPath() + fileName + "."
						+ extName);
				return projectProperties.getFileConfig().getFileRootImagesPath() + fileName + "." + extName;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}
}
